package com.sheyu.mall.product.exception;

import com.sheyu.common.exception.BizCodeEnume;
import com.sheyu.common.exception.CategoryException;
import com.sheyu.common.exception.MYSQLException;
import com.sheyu.common.exception.RRException;
import com.sheyu.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * @author sheyu
 * @date 2020/8/2 10:43 上午
 */


@Slf4j
@RestControllerAdvice(basePackages = "com.sheyu.mall.product.app")
public class MallException {

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handlerValidException(MethodArgumentNotValidException e){
        BindingResult result = e.getBindingResult();

        Map<String,String> map = new HashMap<>();

        result.getFieldErrors().forEach((item)->{
            String message = item.getDefaultMessage();
            String field = item.getField();
            map.put(field,message);
        });
        return R.error(BizCodeEnume.VALID_EXCEPTION.getCode(),BizCodeEnume.VALID_EXCEPTION.getMsg()).put("data",map);
    }
    /**
    @ExceptionHandler(value = Throwable.class)
    public R handleException(Throwable throwable){
        return R.error(BizCodeEnume.UNKNOW_EXCEPTION.getCode(),BizCodeEnume.UNKNOW_EXCEPTION.getMsg());
    }*/
    @ExceptionHandler(value = MYSQLException.class)
    public R handlerMysqlException(MYSQLException e){
        return R.error(BizCodeEnume.MYSQL_NOTEQUAL_EXCEPTION.getCode(),BizCodeEnume.MYSQL_NOTEQUAL_EXCEPTION.getMsg());
    }
    @ExceptionHandler(value = Exception.class)
    public R handlerException(Exception e){
        return R.error(BizCodeEnume.UNKNOW_EXCEPTION.getCode(),BizCodeEnume.UNKNOW_EXCEPTION.getMsg());
    }
    @ExceptionHandler(value = CategoryException.class)
    public R handlerCategoryException(CategoryException e){
        return R.error(BizCodeEnume.CATEGORY_PROBLEM_EXCEPTIOM.getCode(),BizCodeEnume.CATEGORY_PROBLEM_EXCEPTIOM.getMsg());
    }

    @ExceptionHandler(value = RRException.class)
    public R handlerRRException(RRException e){
        return R.error(BizCodeEnume.UNKNOW_EXCEPTION.getCode(),e.getMsg());
    }
}
